package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;

import com.itheima.pojo.R;
import com.itheima.service.CategoryService;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;



import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/page")
    public R page(Integer page, Integer pageSize){

        log.info("开启菜品分类分页查询");
        Page<Category> categoryPage= new Page<>(page, pageSize);

        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Category::getSort);


        categoryService.page(categoryPage,lqw);

        return R.success(categoryPage);

    }

    @PostMapping
    public R insertCategory( @RequestBody Category category){
        log.info("开始添加分类...");
        categoryService.insert(category);
        return R.success("添加分类成功!");
    }

    @DeleteMapping()
    public R delete(Long id)  {
        log.info("开始删除分类...");
        categoryService.deleteById(id);
        return R.success("删除分类成功!");
    }

    @PutMapping
    public R update(@RequestBody Category category){
        log.info("开始修改分类信息...");
        categoryService.update(category);

        return R.success("修改分类成功!");


    }

    @GetMapping("/list")
    public R list(Category category){
        log.info("显示菜品分类");

        String key="category_"+category.getType();

        List<Category> categoryList = (List<Category>) redisTemplate.opsForValue().get(key);
        if(categoryList!=null){
            return R.success(categoryList);
        }

        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(category.getType()!=null,Category::getType,category.getType());
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list=categoryService.list(lqw);
        redisTemplate.opsForValue().set(key,list,1, TimeUnit.HOURS);
        return R.success(list);
    }


}
